package com.tanhua.appserver.service;

import com.tanhua.appserver.exception.BusinessException;
import com.tanhua.appserver.hanlder.UserHolder;
import com.tanhua.dubbointerface.api.BlackListApi;
import com.tanhua.dubbointerface.api.QuestionApi;
import com.tanhua.dubbointerface.api.SettingsApi;
import com.tanhua.dubbointerface.api.UserApi;
import com.tanhua.model.domain.BlackList;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.SettingsVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class SettingsService {
    @DubboReference
    private SettingsApi settingsApi;
    @DubboReference
    private QuestionApi questionApi;
    @DubboReference
    private BlackListApi blackListApi;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private RedisTemplate redisTemplate;
    //缓存验证码前缀
    private String preCode="CHECK_CODE_";

    /**
     * 通用设置数据回显
     * @param userId
     * @param phone
     * @return
     */
    public SettingsVo getSettings(Long userId,String phone) {
        Settings settings=settingsApi.findSettingsByUserId(userId);
        Long id =null;
        if (settings==null){
            settings=new Settings();
            settings.setGonggaoNotification(true);
            settings.setLikeNotification(true);
            settings.setPinglunNotification(true);
            settings.setUserId(userId);
            id =settingsApi.save(settings);
            settings.setId(id);
        }
        id=settings.getId();
        SettingsVo settingsVo = new SettingsVo();
        settingsVo.setId(id);
        settingsVo.setPhone(phone);
        Question question = questionApi.findQuestionByUserId(userId);
        if (question==null){
            question =new Question();
            question.setUserId(userId);
            question.setTxt("你喜欢编程吗？");
            questionApi.save(question);
        }
        String txt = question.getTxt();
        settingsVo.setStrangerQuestion(txt);
        return settingsVo;
    }

    /**
     * 获取通知设置数据
     * @param userId
     * @return
     */
    public Settings findSettingByUserId(Long userId) {
        return settingsApi.findSettingsByUserId(userId);
    }

    /**
     * 更新设置
     * @param settings
     */
    public void update(Settings settings) {
        settingsApi.update(settings);
    }

    /**
     * 取消黑名单
     * @param uid
     */
    public void deleteBlacklist(long uid) {
        BlackList blackList=blackListApi.findByUserId(uid);
        settingsApi.deleteBlacklist(blackList);
    }


    /**
     * 修改手机号码发送验证码
     *
     */
    public void sendVerificationCode() {
        //获取当前手机号
        String phone = UserHolder.getMobile();
        //这个是产生六位随机的数字
//        String code = RandomStringUtils.randomNumeric(6);
        //这里可以加入阿里云短信服务
        //为了方便后面测试code设为123456
        String code="123456";
        //将验证码存入redis中并设置过期时间
        redisTemplate.opsForValue().set(preCode+phone,code, Duration.ofMinutes(5));

    }

    /**
     * 检查修改号码时输入验证码是否正确
     *
     * @param code
     * @return
     */
    public boolean checkVerificationCode(String code) {
        String phone = UserHolder.getMobile();
        //判断redis中依据phone(key)存储的checkCode是否和code相同，是否为空
        String checkCode = (String) redisTemplate.opsForValue().get(preCode + phone);
        if (StringUtils.isEmpty(checkCode)){
            //不存在则抛出异常
            throw new BusinessException(ErrorResult.fail());
        }
        //如果验证不通过返回false
        if (!checkCode.equals(code)){
            return false;
        }
        //移除redis中的验证码,返回true
        redisTemplate.delete(preCode + phone);
        return true;
    }

    public void updatePhone(String phone) {
        String curPhone = UserHolder.getMobile();
        //查询电话信息是否已经被注册
        //调用settingsService中的findUserById查询要修改的电话是否存在如果存在，抛出异常
        User user = userApi.findUserBymobile(phone);
        if (user!=null){
            //被注册，则直接抛出用户已经注册异常
            throw new BusinessException(ErrorResult.mobileError());
        }
        //到这一步说明没有，可以注册
        user = userApi.findUserBymobile(curPhone);
        user.setMobile(phone);
        userApi.update(user);

    }
}
